package be.ipl.finito.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.finito.domaine.Joueur;
import be.ipl.finito.domaine.Partie;
import be.ipl.finito.exceptions.BizException;
import be.ipl.finito.threads.TimeoutCreation;
import be.ipl.finito.usecases.GestionParties;

@SuppressWarnings("serial")
@WebServlet(name = "creerPartie.html")
public class CreerPartie extends HttpServlet implements Servlet {

	@EJB
	private GestionParties gestionParties;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RequestDispatcher rd = getServletContext().getNamedDispatcher(
				"CreerPartie");
		rd.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		Joueur joueur = (Joueur) session.getAttribute("joueur");
		String nomPartie = req.getParameter("nomPartie");

		try {
			Partie partie = gestionParties.creerPartie(joueur, nomPartie);
			@SuppressWarnings("unchecked")
			List<Partie> parties = (List<Partie>) session
					.getAttribute("parties");
			if (parties == null) {
				parties = new ArrayList<Partie>();
			}
			parties.add(partie);
			ServletContext sc = this.getServletContext();
			sc.setAttribute(""+partie.getId(), true);
			new TimeoutCreation(sc,partie).start();
			synchronized (session) {
				session.setAttribute("parties", parties);
			}
			resp.sendRedirect("attente.html?id=" + partie.getId());
			return;
		} catch (BizException e) {
			req.setAttribute("messageErreur", e.getMessage());
		}
		doGet(req, resp);
	}
}